package lwk.thread.syn;

/**
 * @author:lwk
 * @create: 2022-08-03 19:37
 * @Description: 线程不安全的银行取钱
 */
public class SafeBank {
    public static void main(String[] args) {
        Account2 account = new Account2(100, "结婚基金");

        Drawing2 zhangFu = new Drawing2(account, 50, "丈夫");
        Drawing2 qiZi = new Drawing2(account, 100, "妻子");

        zhangFu.start();
        qiZi.start();

    }
}

// 账户
class Account2 {
    // 余额
    int money;
    // 账户
    String name;

    public Account2(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

// 银行：模拟取款
class Drawing2 extends Thread{
    // 账户
    Account2 account;
    // 取多少钱
    int drawingMoney;
    // 现在手上有多少钱
    int nowMoney;

    public Drawing2 (Account2 account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
        //this.nowMoney = nowMoney;
    }

    @Override
    public void run() {

        // 锁的对象就是变化的量，需要增删改的对象
        synchronized (account) {
            // 判断有没有钱
            if (account.money-drawingMoney<0) {
                System.out.println(Thread.currentThread().getName()+"余额不足");
                return;
            }

            //sleep放大问题发生可能性
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 卡里余额 = 卡里余额 - 你取的钱
            account.money = account.money - drawingMoney;

            // 现在手上有多少钱 = 现在手上有多少钱 + 你取的钱
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name+"余额为："+account.money);

            System.out.println(Thread.currentThread().getName()+"手里的钱："+nowMoney);
        }



    }

}